package com.jlnk.servicedemo.views;

import android.Manifest;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.jlnk.servicedemo.R;
import com.jlnk.servicedemo.adapter.MediaCursorAdapter;
import com.jlnk.servicedemo.entity.MediaItem;
import com.jlnk.servicedemo.event.MusicEvent;
import com.jlnk.servicedemo.service.CustomService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MusicListActivity extends AppCompatActivity implements View.OnClickListener,
        AdapterView.OnItemClickListener, CustomService.OnMusicPlayStateChangeListener,
        SeekBar.OnSeekBarChangeListener {
    public static final int UPDATE_PROGRESS = 1;
    private static final int REQUEST_READ_MEDIA_AUDIO = 1;
    private static final int REQUEST_READ_MEDIA_IMAGES = 2;
    private ContentResolver mContentResolver;
    private ListView mPlaylist; // 播放列表
    private TextView tvBottomTitle;
    private TextView tvBottomArtist;
    private ImageView ivAlbumThumbnail;
    private ImageView ivPlay;
    private SeekBar pbProgress; // 播放进度条
    private TextView mTimeView; // 展示播放时间
    private MediaCursorAdapter mCursorAdapter;
    private CustomService mService;
    private Cursor mCursor;
    private MyServiceConnection mConnection;
    private int mDuration; // 总进度(总时间)
    private boolean mPlayStatus = true;
    private int mCurrPosition;
    private List<MediaItem> playlist = new ArrayList<>();
    private int currentSongIndex = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_list);
        mPlaylist = findViewById(R.id.music_list);
        mCursorAdapter = new MediaCursorAdapter(this);
        mPlaylist.setAdapter(mCursorAdapter);
        mPlaylist.setOnItemClickListener(this);
        ivPlay = findViewById(R.id.iv_play);
        ivPlay.setOnClickListener(this);
        tvBottomTitle = findViewById(R.id.tv_bottom_title);
        tvBottomArtist = findViewById(R.id.tv_bottom_artist);
        ivAlbumThumbnail = findViewById(R.id.iv_thumbnail);
        ivAlbumThumbnail.setOnClickListener(this);
        pbProgress = findViewById(R.id.progress);
        pbProgress.setOnSeekBarChangeListener(this);
        mTimeView = findViewById(R.id.time);
        mConnection = new MyServiceConnection();
        mContentResolver = getContentResolver();
        requestPermission();
        initializePlaylist();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, CustomService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_play) {
            mPlayStatus = !mPlayStatus;
            if (mPlayStatus) {
                mService.play();
                ivPlay.setImageResource(R.drawable.baseline_pause_circle_outline_24);
            } else {
                mService.pause();
                ivPlay.setImageResource(R.drawable.baseline_play_circle_outline_24);
            }
        } else if (id == R.id.iv_thumbnail) {
            Intent intent = new Intent(MusicListActivity.this, MusicActivity.class);
            startActivity(intent);
        }
    }

    private List<MediaItem> initializePlaylist() {
        playlist.add(new MediaItem("Song 1", "Artist 1", R.raw.song2));
        playlist.add(new MediaItem("Song 2", "Artist 2", R.raw.song1));
        playlist.add(new MediaItem("Song 3", "Artist 3", R.raw.song3));
        currentSongIndex = 0;
        playCurrentSong();
        return playlist;
    }

    private void playCurrentSong() {
        if (currentSongIndex >= 0 && currentSongIndex < playlist.size()) {
            MediaItem item = playlist.get(currentSongIndex);
            playSong(item.getResId(), item.getTitle(), item.getArtist());
        }
    }

    private void playSong(int resId, String title, String artist) {
        Intent serviceIntent = new Intent(MusicListActivity.this, CustomService.class);
        serviceIntent.putExtra("resId", resId);
        serviceIntent.putExtra("title", title);
        serviceIntent.putExtra("artist", artist);
        startService(serviceIntent);
        tvBottomTitle.setText(title);
        tvBottomArtist.setText(artist);
    }

    private void playNextSong() { // 自动播放下一首
        if (mCursor != null) {
            if (mCursor.moveToNext()) { // 游标向后移动，如不成功走到 else if
                // mCurrPosition++;
            } else if (mCursor.moveToFirst()) { // 游标移动到第一条数据
                // mCurrPosition = 0;
            }
            getDataByCursor(mCursor);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Cursor cursor = mCursorAdapter.getCursor();
        if (cursor != null && cursor.moveToPosition(position)) {
            getDataByCursor(cursor);
        }
    }

    private void getDataByCursor(Cursor cursor) {
        int titleIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        // 媒体地址
        int dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
        if (titleIndex >= 0 && artistIndex >= 0) {
            String title = cursor.getString(titleIndex);
            String artist = cursor.getString(artistIndex);
            String data = cursor.getString(dataIndex);
            Intent serviceIntent = new Intent(MusicListActivity.this,
                    CustomService.class);
            serviceIntent.putExtra("data", data);
            serviceIntent.putExtra("title", title);
            serviceIntent.putExtra("artist", artist);
            startService(serviceIntent);

            if (tvBottomTitle != null) {
                tvBottomTitle.setText(title);
            }
            if (tvBottomArtist != null) {
                tvBottomArtist.setText(artist);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMusicEvent(MusicEvent event) {
        String msg = event.getMessage();
        if (msg.equals("play")) {
            if (mService != null) {
                mDuration = mService.getDuration();
                pbProgress.setMax(mDuration);
                new Thread(new MusicProgressRunnable()).start();
                updateNowPlayingInfo();
            }
        } else if (msg.equals("complete")) {
            playNextSong();
        }
    }

    private void updateNowPlayingInfo() {
        if (mService != null) {
            String title = mService.getSongTitle();
            String artist = mService.getArtistName();
            tvBottomTitle.setText(title);
            tvBottomArtist.setText(artist);
        }
    }

    @Override
    public void onPlayStart() {
        if (mService != null) {
            mDuration = mService.getDuration();
            pbProgress.setMax(mDuration);
            new Thread(new MusicProgressRunnable()).start();
            updateNowPlayingInfo();
            mCurrPosition = mService.getCurrentPosition(); // 获取当前播放位置
            pbProgress.setProgress(mCurrPosition); // 设置 SeekBar 进度为当前播放位置
            mTimeView.setText(formatTime(mCurrPosition) + "/" + formatTime(mDuration));
        }
    }


    @Override
    public void onPlayStop() {

    }

    @Override
    public void onPlayComplete() {
        playNextSong();
    }

    @Override
    public void onProgressUpdate(int currentPosition, int duration) {

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (mService != null && fromUser) {
            mService.seekTo(progress); // 拖动进度条，改变播放进度
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    private class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((CustomService.MyBinder) service).getService();
            mService.setOnMusicPlayStateChangeListener(MusicListActivity.this);
            List<MediaItem> playlist = initializePlaylist();
            if (playlist != null && !playlist.isEmpty()) {
                mService.setPlaylist(playlist);
            } else {
                Log.e("MusicListActivity", "Playlist is empty after initialization.");
            }
            initPlaylist();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_PROGRESS:
                    int position = msg.arg1;
                    pbProgress.setProgress(position); // 设置当前进度(当前时间)
                    mTimeView.setText(formatTime(position) + "/" + formatTime(mDuration)); // 当前时间/总时间
                    break;
                default:
                    break;
            }
        }
    };

    private class MusicProgressRunnable implements Runnable {
        public MusicProgressRunnable() {
        }

        @Override
        public void run() {
            boolean mThreadWorking = true;
            while (mThreadWorking) {
                try {
                    if (mService != null) {
                        int position = mService.getCurrentPosition();
                        Message message = new Message();
                        message.what = UPDATE_PROGRESS;
                        message.arg1 = position;
                        mHandler.sendMessage(message);
                    }
                    mThreadWorking = mService.isPlaying();
                    Thread.sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initPlaylist() { // 查询媒体数据，初始化播放列表
        // 查询媒体库
        Uri contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        // 在这里的projection中添加上专辑和音乐地址的查询，这样下面的itemClickListener才能获得媒体地址，mMediaPlayer才能启动
        String[] projection = new String[]{
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.DATA};
        String selection = MediaStore.Audio.Media.DATA + " LIKE ? ";
        String[] selectionArgs = {"%/Music/QQMusic/%"};
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";

        if (mContentResolver != null) {
            mCursor = mContentResolver.query(
                    contentUri, projection, selection, selectionArgs, sortOrder);
            mCursorAdapter.changeCursor(mCursor);
            mCursorAdapter.notifyDataSetChanged();
        }
    }

    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_MEDIA_AUDIO);
        } else {
            initializePlaylist();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_READ_MEDIA_AUDIO) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initializePlaylist();
            } else {
                // 权限被拒绝，无法初始化播放列表
                Log.e("MusicListActivity", "Permission denied, cannot initialize playlist.");
            }
        }
    }

    private String formatTime(int millis) {
        int totalSeconds = millis / 1000;
        int minutes = totalSeconds / 60;
        int seconds = totalSeconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }
}